<script lang="ts" setup>
import dayjs from 'dayjs'
import { ElMessageBox, ElButton } from 'element-plus'

function cloneDeep(data: any) {
  return JSON.parse(JSON.stringify(data))
}

const list = reactive({ value: [] })
const resultList = computed(() => list.value?.filter(item => !keyword.value || item.cmd?.includes(keyword.value)) || [])

const current = ref(-1)
const keyword = ref('')

const currentPath = ref('')

utools.onPluginEnter(async action => {
  console.log('进入应用', action)
  init()
  keyword.value = action.payload.trim().replace(/^\.?\>?/, '')
  if (keyword.value) {
    utools.setSubInputValue(keyword.value)
    if (action.code === 'current_iTerm') {
      currentPath.value = await utools.readCurrentFolderPath()
    } else {
      currentPath.value = ''
    }
    services.execCommand(keyword.value, currentPath.value)
    addHistory(keyword.value)
  }
})
onMounted(() => {
  window.addEventListener('keydown', e => {
    if (e.key === 'ArrowUp') {
      if (current.value < 1) current.value = resultList.value.length - 1
      else current.value--
    } else if (e.key === 'ArrowDown') {
      if (current.value >= resultList.value.length - 1) current.value = 0
      else current.value++
    } else if (e.key === 'Enter') {
      console.log('回车', resultList.value, keyword.value)
      const _cmd = keyword.value?.trim()
      if (!resultList.value.length && _cmd) {
        services.execCommand(_cmd, currentPath.value)
        addHistory(_cmd)
      } else {
        onSelect()
      }
    }
  })
})

function init() {
  getHistory()
  utools.setSubInput(
    event => {
      console.log('输入框change', event.text)
      current.value = 0
      keyword.value = event.text
    },
    '请输入命令',
    true
  )
}

function addHistory(cmd) {
  if (!cmd) return
  const _list = list.value?.slice() || []
  const _obj = _list.find(item => item.cmd === cmd)
  if (_obj) {
    _obj.time = dayjs().format('YYYY-MM-DD HH:mm:ss')
  } else {
    _list.push({
      cmd,
      desc: '',
      time: dayjs().format('YYYY-MM-DD HH:mm:ss')
    })
  }
  saveDB(_list)
}

function getHistory() {
  const _history = window.utools.db.get('history')
  list.value = _history?.data || []
}

function saveDB(data) {
  const doc = {
    _id: 'history',
    data: cloneDeep(data || []).sort((a, b) => dayjs(b.time).valueOf() - dayjs(a.time).valueOf())
  }
  let _history = window.utools.db.get('history')
  if (_history) {
    doc._rev = _history._rev
  }
  utools.db.put(doc)
}

function onSelect() {
  const item = resultList.value[current.value]
  if (!item) return
  services.execCommand(item.cmd, currentPath.value)
  addHistory(item.cmd)
}

async function onDelete(item) {
  await ElMessageBox.confirm('确定删除该条命令吗？', '删除', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
  list.value.splice(
    list.value.findIndex(o => o.cmd === item.cmd),
    1
  )
  saveDB(list.value)
}
function onCopy(item) {
  utools.copyText(item.cmd)
  window.utools.showNotification(`复制命令：${item.cmd}`)
}
async function onSetDesc(item) {
  const { value } = await ElMessageBox.prompt('', '命令备注', {
    confirmButtonText: '确认',
    cancelButtonText: '取消'
  })
  if (!value) return
  const obj = list.value.find(o => o.cmd === item.cmd)
  obj.desc = value
  saveDB(list.value)
}

async function onClear() {
  await ElMessageBox.confirm('确定清空历史命令吗？', '清空', {
    confirmButtonText: '确认',
    cancelButtonText: '取消'
  })
  list.value = []
  saveDB([])
}

function onImport() {
  const files = utools.showOpenDialog({
    filters: [{ name: '*.json', extensions: ['json'] }],
    properties: ['openFile']
  })
  if (!files?.[0]) return
  const fileContent = services.readFile(files[0])
  try {
    const data = JSON.parse(fileContent)
    if (!Array.isArray(data)) {
      window.utools.showNotification('JSON格式不正确')
      return
    }

    data.forEach(item => {
      if (!item.cmd) return
      const _obj = list.value.find(o => o.cmd === item.cmd)
      if (_obj) {
        _obj.desc = item.desc
        _obj.time = dayjs().format('YYYY-MM-DD HH:mm:ss')
      } else {
        list.value.push({
          cmd: item.cmd,
          desc: item.desc,
          time: dayjs().format('YYYY-MM-DD HH:mm:ss')
        })
      }
    })
    saveDB(list.value)
  } catch (e) {
    window.utools.showNotification('JSON格式不正确')
  }
}

function onExport() {
  services.export(JSON.stringify(list.value))
}
</script>

<template>
  <ul class="m-0 p-0 w-full h-full">
    <li class="px-12 py-6" :class="{ active: current === index }" v-for="(item, index) in resultList" :key="index" @mouseenter="() => (current = index)" @click="onSelect">
      <div class="text-16 sl-ellipsis-1">{{ item.cmd }}</div>
      <div class="flex justify-between text-10 text-#999 mt-5 lh-16">
        <div class="flex-1 sl-ellipsis-1 mr-20">
          <span v-if="item.desc" class="mr-30">{{ item.desc }}</span
          ><span>{{ item.time }}</span>
        </div>

        <div class="flex justify-end">
          <div class="btn text-#74b9ff" @click.stop="onSetDesc(item)">备注</div>
          <div class="btn text-#00a8ff" @click.stop="onCopy(item)">复制</div>
          <div class="btn text-#95a5a6" @click.stop="onDelete(item)">删除</div>
        </div>
      </div>
    </li>
  </ul>
  <div class="h-32 w-full"></div>
  <div class="fixed bottom-0 left-0 right-0 bottom h-32 w-full flex justify-end align-center px-20 box-border bg-#F4F4F4">
    <el-button link type="primary" :disabled="!list.value?.length" @click="onClear">清空历史</el-button>
    <el-button link type="primary" @click="onImport">导入命令</el-button>
    <el-button link type="primary" :disabled="!list.value?.length" @click="onExport">导出命令</el-button>
  </div>
</template>

<style scoped lang="scss">
li {
  list-style: none;
  cursor: pointer;
  position: relative;
  &::before {
    content: '';
    height: 2px;
    background: #778beb;
    display: inline-block;
    position: absolute;
    left: 0;
    bottom: 0;
    width: 0;
    transition: width 0.3s;
  }
  &.active {
    background-color: #dfe2e6;
    &::before {
      width: 100%;
    }
  }
}
.btn {
  border-radius: 4px;
  border: 1px solid;
  padding: 0 10px;
  line-height: 16px;
  font-size: 10px;
  transition: all 0.3s;
  cursor: pointer;
  &:hover {
    transform: scale(1.2);
  }
  + .btn {
    margin-left: 10px;
  }
}
</style>
